import 'package:base_flutter/base_flutter.dart' as b;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/a_elder/models/upload_entity.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'dart:convert';
import 'dart:io';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:dio/dio.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/util/utils.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../login/page/user_manager.dart';
import '../../util/ext_utils.dart';




class AddQualificationsPage extends StatefulWidget {
  final VoidCallback? callBack;
  final Upload? info;
  final int? type; //3 健康证 4资格证
  AddQualificationsPage({Key? key, this.callBack, this.info, this.type});
  @override
  _AddQualificationsPageState createState() => _AddQualificationsPageState();
}

class _AddQualificationsPageState extends State<AddQualificationsPage> {
  TextEditingController textFieldEditer = TextEditingController();

  File? image;
  Upload? upload;
  int _fileId = 0;
  @override
  void initState() {
    super.initState();

    if (widget.info != null) {
      textFieldEditer.text = widget.info!.fileDesc??"";
      _fileId = widget.info!.fileId??0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('新增证书'),
        elevation: 0.5,
        actions: <Widget>[
          TextButton(
            onPressed: _send,
            child: Text(
              '提交',
              style: TextStyle(fontSize: 16, color: Colours.app_main),
            ),
          )
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(20),
            child: Text(
              '证书名称',
              style: TextStyles.textDark16,
            ),
          ),
          Container(
            padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
            color: Colors.white,
            alignment: Alignment.topLeft,
            child: TextField(
              controller: textFieldEditer,
              maxLines: 1,
              autofocus: false,
              decoration: InputDecoration(
                hintText: "请输入证件名称",
                hintMaxLines: 20,
                fillColor: Colours.bg_color,
                filled: true,
                border: InputBorder.none,
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 20),
            child: ElevatedButton(
              child: Text("选择照片"),
              onPressed: _pickImageFromSource,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          image != null
              ? _imageView(image)
              : (widget.info != null
                  ? _imageUrlView(widget.info?.fileId)
                  : Container()),
        ],
      ),
    );
  }

  _send() {
    if (_fileId <= 0) {
      Toast.show('请选择图片');
      return;
    }
    if (textFieldEditer.text.isEmpty) {
      Toast.show('请输入证件名称');
      return;
    }

    var map = {
      'fileId': _fileId,
      'pictureType': widget.type,
      'fileDesc': textFieldEditer.text
    };
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.saveBean}?${requestParams(map)}')
        .then((r) {
      ///
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///选择图片方式
  _pickImageFromSource() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机"),
                onTap: () async {
                  Navigator.pop(context);
                  Permission.camera.checkRequestPermission(context,onSuccess: () async {
                    var imageFile =
                        await ImagePicker().pickImage(source: ImageSource.camera);
                    if(imageFile!=null){
                      setState(() {
                        image = File(imageFile.path);
                        _upLoadImage(File(imageFile.path));
                      });
                    }
                  },msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限");
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("相册"),
                onTap: () async {
                  Navigator.pop(context);
                  var isAndroid13 = await isAndroid13OrAbove();
                  if(isAndroid13){
                    Permission.photos.checkRequestPermission(context, onSuccess: () async {
                      var imageFile =
                      await ImagePicker().pickImage(source: ImageSource.gallery);
                      if(imageFile!=null){
                        setState(() {
                          image = File(imageFile.path);
                          _upLoadImage(File(imageFile.path));
                        });
                      }
                      print(imageFile);
                    }, msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限");
                  }else{
                    Permission.storage.checkRequestPermission(context, onSuccess: () async {
                      var imageFile =
                      await ImagePicker().pickImage(source: ImageSource.gallery);
                      if(imageFile!=null){
                        setState(() {
                          image = File(imageFile.path);
                          _upLoadImage(File(imageFile.path));
                        });
                      }
                      print(imageFile);
                    }, msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限");
                  }

                },
              ),
            ],
          );
        });
  }

  ///上传
  _upLoadImage(File image) async {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    String path = image.path;
    print(path);
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var fileType = name.split(".").last;
    FormData formData = new FormData.fromMap({
      'fileType': fileType,
      'fileToUpload': await MultipartFile.fromFile(path, filename: name),
    });
    HttpUtil.instance.getDio().post(HttpApi.upload, data: formData).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Toast.show('图片上传成功');
            Upload model = Upload.fromJson(map['data']);
            setState(() {
              upload = model;
              _fileId = model.id??0;
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

/*图片控件*/
  Widget _imageView(imgPath) {
    if (imgPath == null) {
      return Container();
    } else {
      return Image.file(
        imgPath,
        width: 150,
        height: 150,
      );
    }
  }

  Widget _imageUrlView(url) {
    String url1 = '${HttpApi.imageHead}$url';
    print(url1);
    if (url == null) {
      return Container();
    } else {
      return CachedNetworkImage(
        width: 150,
        height: 150,
        fit: BoxFit.fill,
        imageUrl: url1,
          httpHeaders: {"Cookie":UserManager.cookieStr},
        placeholder: (context, url) => new ProgressView(),
        errorWidget: (context, url, error) => new Icon(Icons.error),
      );
    }
  }
}
